package com.zrrd.yt.order.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zrrd.yt.common.util.HttpClientUtil;
import com.zrrd.yt.model.enums.OrderStatus;
import com.zrrd.yt.model.enums.ProcessStatus;
import com.zrrd.yt.model.order.OrderDetail;
import com.zrrd.yt.model.order.OrderInfo;
import com.zrrd.yt.order.mapper.OrderDetailMapper;
import com.zrrd.yt.order.mapper.OrderInfoMapper;
import com.zrrd.yt.order.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements OrderService {

    @Autowired
    private OrderDetailMapper detailMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Value("${ware.url}")
    private String WARE_URL;

    @Override
    @Transactional
    public Long saveOrderInfo(OrderInfo orderInfo) {
        //设置订单总金额
        orderInfo.sumTotalAmount();
        //设置订单状态
        orderInfo.setOrderStatus(OrderStatus.UNPAID.name());
        //设置第三方交易编号
        String outTradeNo = "yt" + System.currentTimeMillis() + "" + new Random().nextInt(1000);
        orderInfo.setOutTradeNo(outTradeNo);
        //设置创建时间
        orderInfo.setCreateTime(new Date());
        //设置失效时间
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, 1);
        orderInfo.setExpireTime(calendar.getTime());
        //设置进度状态
        orderInfo.setProcessStatus(ProcessStatus.UNPAID.name());
        //设置订单描述--->将订单明细中每个商品的名称拼接 最多只展示100字
        StringBuilder builder = new StringBuilder();
        List<OrderDetail> orderDetailList = orderInfo.getOrderDetailList();
        for (OrderDetail detail : orderDetailList) {
            builder.append(detail.getSkuName() + " ");
        }
        if (builder.toString().length() > 100) {
            orderInfo.setTradeBody(builder.toString().substring(0, 100));
        } else {
            orderInfo.setTradeBody(builder.toString());
        }
        //保存订单数据
        this.save(orderInfo);
        //保存订单明细数据
        for (OrderDetail detail : orderDetailList) {
            detail.setOrderId(orderInfo.getId());
            detail.setCreateTime(new Date());
            detailMapper.insert(detail);
        }

        //返回订单ID
        return orderInfo.getId();
    }

    @Override
    public String getTradeNo(String userId) {
        //生成流水号
        String tradeNo = UUID.randomUUID().toString().replaceAll("-", "");
        //存入到Redis
        String key = "user:" + userId + ":tradeCode";
        redisTemplate.opsForValue().set(key, tradeNo);
        //返回
        return tradeNo;
    }

    @Override
    public boolean checkTradeNo(String userId, String tradeCode) {
        //从redis中取出流水号
        String key = "user:" + userId + ":tradeCode";
        String redisTradeCode = (String) redisTemplate.opsForValue().get(key);
        //返回比较结果
        return tradeCode.equals(redisTradeCode);
    }

    @Override
    public void deleteTradeNo(String userId) {
        //从redis中删除流水号
        String key = "user:" + userId + ":tradeCode";
        redisTemplate.delete(key);
    }

    @Override
    public boolean checkStock(Long skuId, Integer skuNum) {
        //发起远程请求库存服务校验库存接口
        String result = HttpClientUtil.doGet(WARE_URL + "/hasStock?skuId=" + skuId + "&num=" + skuNum);
        //返回校验结果
        return "1".equals(result);
    }
}
